package com.ruoyi.lock.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.lock.domain.ABuildHome;
import com.ruoyi.lock.domain.AHomeUser;
import com.ruoyi.lock.domain.ATenantkey;
import com.ruoyi.lock.domain.ATenantuser;
import com.ruoyi.lock.service.IABuildHomeService;
import com.ruoyi.lock.service.IAHomeUserService;
import com.ruoyi.lock.service.IATenantkeyService;
import com.ruoyi.lock.service.IATenantuserService;
import com.ruoyi.lock.service.IOracleDataSyncService;
import com.ruoyi.utils.login.QRCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;
import java.util.Date;
import java.util.Calendar;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 学生信息信息Controller
 *
 * @author arvin
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/tenantuser/tenant")
public class ATenantuserController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(ATenantuserController.class);

    @Autowired
    private IATenantuserService aTenantuserService;

    @Autowired
    private IATenantkeyService aTenantkeyService;
    @Autowired
    private IABuildHomeService iaBuildHomeService;

    @Autowired
    private IOracleDataSyncService oracleDataSyncService;

    @Value("${app.domain}")
    private String appDomain;



    /**
     * 查询学生信息信息列表
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:list')")
    @GetMapping("/list")
    public TableDataInfo list(ATenantuser aTenantuser)
    {
        startPage();
        List<ATenantuser> list = aTenantuserService.selectATenantuserList(aTenantuser);
        return getDataTable(list);
    }

    @GetMapping("/list3")
    public TableDataInfo list3(ATenantuser aTenantuser)
    {
        List<ATenantuser> list = aTenantuserService.selectATenantuserList3(aTenantuser);
        return getDataTable(list);
    }

    @GetMapping("/listruzhu")
    public TableDataInfo listRuZhu(ATenantuser aTenantuser)
    {

        List<ATenantuser> list = aTenantuserService.selectATenantuserListRuZhu(aTenantuser);
        return getDataTable(list);
    }

    @GetMapping("/listNotRuZhu")
    public TableDataInfo listNotRuZhu(ATenantuser aTenantuser) {
        startPage();
        List<ATenantuser> list = aTenantuserService.selectATenantuserListNotRuZhu(aTenantuser);
        return getDataTable(list);
    }


    /**
     * 导出学生信息信息列表
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:export')")
    @Log(title = "学生信息信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ATenantuser aTenantuser)
    {
        List<ATenantuser> list = aTenantuserService.selectATenantuserList(aTenantuser);
        for (ATenantuser tenantuser : list) {

            if(tenantuser.getRoomCount()>0){
                tenantuser.setRuzhu("已入住");
            }else{
                tenantuser.setRuzhu("未入住");
            }
            if("0".equals(tenantuser.getType())){
                tenantuser.setType("学生");
            }else if("1".equals(tenantuser.getType())) {
                tenantuser.setType("教职工");
            }else if("2".equals(tenantuser.getType())) {
                tenantuser.setType("维护人员");
            }else if("3".equals(tenantuser.getType())) {
                tenantuser.setType("其他");
            }



        }
        ExcelUtil<ATenantuser> util = new ExcelUtil<ATenantuser>(ATenantuser.class);
        util.exportExcel(response, list, "学生信息信息数据");
    }

    /**
     * 获取学生信息信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:query')")
    @GetMapping(value = "/{id:\\d+}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ATenantuser aTenantuser = aTenantuserService.selectATenantuserById(id);
        List<ABuildHome> aBuildHomes = iaBuildHomeService.selectABuildHomeListByUserId(aTenantuser.getId());
        aTenantuser.setABuildHomes(aBuildHomes);
        return success(aTenantuser);
    }

    /**
     * 获取学生信息信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:query')")
    @GetMapping(value = "/roomsWithoutCardKey/{id:\\d+}")
    public AjaxResult roomsWithoutCardKey(@PathVariable("id") Long id)
    {
        ATenantuser aTenantuser = aTenantuserService.selectATenantuserById(id);
        List<ABuildHome> aBuildHomes = iaBuildHomeService.selectABuildHomeListByUserId2(aTenantuser.getId());
        aTenantuser.setABuildHomes(aBuildHomes);
        return success(aTenantuser);
    }
    /**
     * 根据用户ID和房间ID查询入住用户信息
     */
    @GetMapping(value = "/ruzhuinfo/userId")
    public AjaxResult selectATenantuserByIdRuzhu(ATenantuser aTenantuser)
    {
        return success(aTenantuserService.selectATenantuserByIdRuzhu(aTenantuser));
    }

    /**
     * 根据用户ID和房间ID查询入住用户信息（路径参数方式）
     */
    @GetMapping(value = "/ruzhuinfo/{id}/{homeId}")
    public AjaxResult selectATenantuserByIdRuzhuByPath(@PathVariable("id") Long id, @PathVariable("homeId") Long homeId)
    {
        ATenantuser query = new ATenantuser();
        query.setId(id);
        query.setHomeId(homeId);
        return success(aTenantuserService.selectATenantuserByIdRuzhu(query));
    }

    /**
     * 新增学生信息信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:add')")
    @Log(title = "学生信息信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ATenantuser aTenantuser)
    {
        aTenantuser.setIsFlag("1");
        return toAjax(aTenantuserService.insertATenantuser(aTenantuser));
    }

    /**
     * 修改学生信息信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:edit')")
    @Log(title = "学生信息信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ATenantuser aTenantuser)
    {
        return toAjax(aTenantuserService.updateATenantuser(aTenantuser));
    }

    /**
     * 删除学生信息信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:remove')")
    @Log(title = "学生信息信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(aTenantuserService.deleteATenantuserByIds(ids));
    }

    /**
     * 更新学生信息状态（包含钥匙删除逻辑）
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:edit')")
    @Log(title = "学生信息状态更新", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody ATenantuser aTenantuser)
    {
        // 验证请求参数
        if (aTenantuser.getId() == null || aTenantuser.getIsFlag() == null) {
            return AjaxResult.error("参数错误");
        }

        // 获取当前学生信息信息
        ATenantuser currentTenant = aTenantuserService.selectATenantuserById2(aTenantuser.getId());
        if (currentTenant == null) {
            return AjaxResult.error("学生信息不存在");
        }

        if(Objects.equals(currentTenant.getIsFlag(), aTenantuser.getIsFlag())){
            return AjaxResult.success("学生信息已经是退租状态，操作成功");
        }

//        if(currentTenant.getIsFlag()==2&&aTenantuser.getIsFlag() == 1) {
//            return toAjax(aTenantuserService.updateATenantuser(aTenantuser));
//        }else{
//            // 查询学生信息关联的钥匙
//            ATenantkey query = new ATenantkey();
//            query.setTenantId(aTenantuser.getId());
//            List<ATenantkey> keyList = aTenantkeyService.selectATenantkeyList(query);
//            // 删除钥匙
//            if (!keyList.isEmpty()) {
//                return AjaxResult.error("学生信息名下存在钥匙或删除未生效的钥匙，请删除钥匙");
//
//            }
//        }

        return toAjax(aTenantuserService.updateATenantuser(aTenantuser));

    }

    /**
     * 根据身份证号列表批量查询租户信息
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:query')")
    @PostMapping("/batchQueryByIdCardNumbers")
    public AjaxResult batchQueryByIdCardNumbers(@RequestBody List<String> idCardNumbers)
    {
        try {
            List<ATenantuser> list = aTenantuserService.selectATenantuserByIdCardNumbers(idCardNumbers);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("批量查询租户信息失败", e);
            return AjaxResult.error("批量查询租户信息失败：" + e.getMessage());
        }
    }

    /**
     * Oracle数据同步 - 同步所有数据
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:sync')")
    @Log(title = "Oracle数据同步", businessType = BusinessType.OTHER)
    @PostMapping("/syncOracle/all")
    public AjaxResult syncOracleAll()
    {
        try {
            logger.info("开始执行Oracle数据同步（全量）");
            // 异步执行同步，不等待完成
            new Thread(() -> {
                try {
                    oracleDataSyncService.syncOracleUserCard("all");
                    logger.info("Oracle数据同步（全量）执行完成");
                } catch (Exception e) {
                    logger.error("Oracle数据同步（全量）执行失败", e);
                }
            }).start();
            
            return AjaxResult.success("Oracle数据同步（全量）已启动，正在后台执行中");
        } catch (Exception e) {
            logger.error("Oracle数据同步（全量）启动失败", e);
            return AjaxResult.error("Oracle数据同步（全量）启动失败：" + e.getMessage());
        }
    }

    /**
     * Oracle数据同步 - 同步当前时间数据
     */
    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:sync')")
    @Log(title = "Oracle数据同步", businessType = BusinessType.OTHER)
    @PostMapping("/syncOracle/current")
    public AjaxResult syncOracleCurrent()
    {
        try {
            logger.info("开始执行Oracle数据同步（增量）");
            
            // 查询用户表中最大的s_update_time时间，直接使用该时间进行增量同步
            Date maxUpdateTime = aTenantuserService.getMaxSUpdateTime();
            if (maxUpdateTime != null) {
                logger.info("执行增量同步，数据库最大s_update_time: {}", maxUpdateTime);
                // 异步执行增量同步，不等待完成
                new Thread(() -> {
                    try {
                        oracleDataSyncService.syncOracleUserCard("current");
                        logger.info("Oracle数据同步（增量）执行完成");
                    } catch (Exception e) {
                        logger.error("Oracle数据同步（增量）执行失败", e);
                    }
                }).start();
                
                return AjaxResult.success("Oracle数据同步（增量）已启动，正在后台执行中");
            } else {
                // 如果没有数据，执行全量同步
                logger.info("未找到s_update_time数据，执行全量同步");
                // 异步执行全量同步，不等待完成
                new Thread(() -> {
                    try {
                        oracleDataSyncService.syncOracleUserCard("all");
                        logger.info("Oracle数据同步（全量）执行完成");
                    } catch (Exception e) {
                        logger.error("Oracle数据同步（全量）执行失败", e);
                    }
                }).start();
                
                return AjaxResult.success("Oracle数据同步（全量）已启动，正在后台执行中");
            }
        } catch (Exception e) {
            logger.error("Oracle数据同步（增量）启动失败", e);
            return AjaxResult.error("Oracle数据同步（增量）启动失败：" + e.getMessage());
        }
    }

    /**
     * Oracle数据同步 - 测试模拟数据
     */
//    @PreAuthorize("@ss.hasPermi('tenantuser:tenant:sync')")
    @Log(title = "Oracle数据同步测试", businessType = BusinessType.OTHER)
    @PostMapping("/syncOracle/test")
    public AjaxResult testOracleSync()
    {
        try {
            logger.info("开始执行Oracle数据同步测试");
            oracleDataSyncService.testOracleDataSync();
            logger.info("Oracle数据同步测试执行完成");
            return AjaxResult.success("Oracle数据同步测试执行成功");
        } catch (Exception e) {
            logger.error("Oracle数据同步测试执行失败", e);
            return AjaxResult.error("Oracle数据同步测试执行失败：" + e.getMessage());
        }
    }
}
